package com.shenjinzheng.apply.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.shenjinzheng.apply.dto.StoreApplyDTO;
import com.shenjinzheng.apply.entity.StoreApply;
import com.shenjinzheng.apply.mapper.StoreApplyMapper;
import com.shenjinzheng.apply.service.StoreApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenjinzheng.merchant.MerchantClient;
import com.shenjinzheng.merchant.entity.MerchantInfo;
import com.shenjinzheng.merchant.entity.Store;
import com.shenjinzheng.sso.SSOClient;
import com.shenjinzheng.sso.entity.Merchant;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 店铺入驻申请表 服务实现类
 * </p>
 *
 * @author shenjinzheng
 * @since 2024-11-10
 */
@Slf4j
@Service
public class StoreApplyServiceImpl extends ServiceImpl<StoreApplyMapper, StoreApply> implements StoreApplyService {

    @Resource
    private HttpServletRequest request;

    @Resource
    private SSOClient ssoClient;

    @Resource
    private MerchantClient merchantClient;

    /**
     * 申请
     *
     * @param storeApply
     */
    @Override
    public void apply(StoreApply storeApply) {
        String token = request.getHeader("Authorization");
        log.info("token:{}", token);
        //因为商户Id和会员Id其实是同一个,所以可以直接用
        String merchantId = ssoClient.getMemberIdByToken();
        storeApply.setMerchantId(merchantId);
        this.save(storeApply);
    }

    /**
     * 审批
     * @param storeApplyDTO
     */
    @Override
    public void approval(StoreApplyDTO storeApplyDTO) {
        //1.根据Id获取店铺申请单的信息
        StoreApply storeApply = this.getById(storeApplyDTO.getId());
        //2.判断status状态是否是未审核,如果是已通过或者未通过,则说明已经被操作过,为保持业务幂等性,抛异常
        if (!"0".equals(storeApply.getStatus())) {
            throw new RuntimeException("申请单状态异常");
        }
        //3.如果是未审核,则改为前端传过来的状态(通过或未通过)
        storeApply.setStatus(storeApplyDTO.getStatus());
        //3.1 未通过还需要说明不通过的原因
        storeApply.setRemark(storeApplyDTO.getRemark());
        this.updateById(storeApply);
        //3.2 申请不通过则不需要做其他事情
        if (!"1".equals(storeApplyDTO.getStatus())){
            return;
        }
        //4. 通过了则生成店铺信息
        //4.1 拷贝申请单中相同字段信息到店铺表
        Store store = new Store();
        BeanUtil.copyProperties(storeApply, store);
        store.setMerchantId(storeApply.getMerchantId());
        store.setStoreApplyId(storeApply.getId());
        merchantClient.saveStore(store);
    }


}
